package com.qiangqiang.service;

import com.qiangqiang.aop.annotation.CheckHasStudent;
import com.qiangqiang.dto.BanDTO;
import com.qiangqiang.dto.LateDTO;
import com.qiangqiang.entity.Ban;
import com.qiangqiang.entity.Late;
import com.qiangqiang.repository.LateReposity;
import com.qiangqiang.repository.StudentRepository;
import com.qiangqiang.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by q on 2018/2/11.
 */
@Slf4j
@Service
public class LateService {

    @Autowired
    private LateReposity lateReposity;

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 增加一条晚归记录
     *
     * @param sId
     */
    @CheckHasStudent
    public void addLateRecord(String sId) {
        lateReposity.insertLate(KeyUtil.getUniqueKey(), sId);
    }

    /**
     * 根据时间间隔查询
     *
     * @param startTime
     * @param finishTime
     * @return
     */
    public List<LateDTO> findByTimeQuantum(String startTime, String finishTime) {
        return lateReposity.queryByTimeQuantum(startTime, finishTime).stream()
                .map(e -> {
                    LateDTO lateDTO = new LateDTO();
                    BeanUtils.copyProperties(e, lateDTO);
                    lateDTO.setName(studentRepository.queryNameBySId(e.getSId()));
                    return lateDTO;
                }).collect(Collectors.toList());
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    public Page<LateDTO> findAllLateRecord(int page, int size){
        PageRequest request = new PageRequest(page, size);
        Page<Late> lates = lateReposity.findAll(request);
        List<LateDTO> lateDTOS = lates.getContent().stream()
                .map(e -> {
                    LateDTO lateDTO = new LateDTO();
                    BeanUtils.copyProperties(e, lateDTO);
                    lateDTO.setName(studentRepository.queryNameBySId(e.getSId()));
                    return lateDTO;
                }).collect(Collectors.toList());
        return new PageImpl(lateDTOS);
    }

    public List<LateDTO> findAllBySId(String sId){
        return lateReposity.queryBySId(sId).stream()
                .map(e->{
                    LateDTO lateDTO=new LateDTO();
                    BeanUtils.copyProperties(e,lateDTO);
                    lateDTO.setName(studentRepository.queryNameBySId(e.getSId()));
                    return lateDTO;
                }).collect(Collectors.toList());
    }
}
